package org.jsola.hr.service.excel;

import com.alibaba.excel.context.AnalysisContext;
import lombok.extern.slf4j.Slf4j;
import org.jsola.common.BeanKit;
import  org.jsola.hr.dto.AttendPunchRecordAddDTO;
import  org.jsola.hr.dto.excel.AttendPunchRecordImportDTO;
import org.jsola.hr.entity.AttendPlanDO;
import org.jsola.hr.entity.EmpInfoDO;
import  org.jsola.hr.exception.HrException;
import org.jsola.hr.query.EmpInfoQuery;
import org.jsola.hr.service.IAttendPlanService;
import  org.jsola.hr.service.IAttendPunchRecordService;
import org.jsola.hr.service.IEmpInfoService;
import org.jsola.hr.vo.excel.ParseResultVO;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author zhr
 */
@Slf4j
public class AttendPunchRecordImportListener extends BaseAnalysisEventListener<AttendPunchRecordImportDTO> {

    /**
     * 入库
     */
    @Override
    public void saveData() {
        log.info("{}条数据，开始存储数据库！", dataList.size());
        if (dataList.size() == 0) {
            log.warn("没有数据需要入库");
            return;
        }
        HrException.notNull(tokenUser, "没有设置当前登录用户");
        IAttendPunchRecordService attendPunchRecordService = BeanKit.getBean(IAttendPunchRecordService.class);
        successCount += attendPunchRecordService.saveExcelDataList(dataList, tokenUser);
        log.info("存储数据库成功！");
    }

    @Override
    protected ParseResultVO<AttendPunchRecordImportDTO> parse(AttendPunchRecordImportDTO data, AnalysisContext context){
        ParseResultVO<AttendPunchRecordImportDTO> parseResultVO = super.parse(data,context);

        parseResultVO.setMsgList(new ArrayList<>());

        IEmpInfoService empInfoService = BeanKit.getBean(IEmpInfoService.class);
        IAttendPlanService attendPlanService = BeanKit.getBean(IAttendPlanService.class);

        // 根据员工姓名和手机号查询员工信息
        EmpInfoDO empInfo = null;
        EmpInfoQuery empInfoQuer = new EmpInfoQuery();
        empInfoQuer.setName(data.getEmpInfoName());
        empInfoQuer.setPhone(data.getPhone());
        List<EmpInfoDO> empInfoDOList = empInfoService.selectDO(empInfoQuer, tokenUser);
        if (empInfoDOList.size() <= 0) {

            parseResultVO.setSuccess(false);
            parseResultVO.getMsgList().add("根据手机号和员工姓名找不到姓名为" + data.getEmpInfoName() + "的员工");
            return parseResultVO;
        }

        empInfo = empInfoDOList.get(0);

        // 查询当前用户使用的考勤规则
        AttendPlanDO attendPlanDO = null;
        List<AttendPlanDO> attendPlanDOList = attendPlanService.getAttendPlan(empInfo.getId(), data.getAttendDate(), tokenUser.getSiteId());
        if (attendPlanDOList == null || attendPlanDOList.size() <= 0) {
            parseResultVO.setSuccess(false);
            parseResultVO.getMsgList().add(empInfo.getName() + "未匹配倒考勤规则");
        }

        return parseResultVO;
    }

}
